Bitwise AND of Numbers Range
LeetCode 201 | Difficulty: Mediumβ
MediumProblem Descriptionβ
Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.
Example 1:
Input: left = 5, right = 7
Output: 4
Example 2:
Input: left = 0, right = 0
Output: 0
Example 3:
Input: left = 1, right = 2147483647
Output: 0
Constraints:
- `0 <= left <= right <= 2^31 - 1`
Topics: Bit Manipulation
Approachβ
Bit Manipulationβ
Operate directly on binary representations. Key operations: AND (&), OR (|), XOR (^), NOT (~), shifts (<<, >>). XOR is especially useful: a ^ a = 0, a ^ 0 = a.
When to use
Finding unique elements, power of 2 checks, subset generation, toggling flags.
Solutionsβ
Solution 1: C# (Best: 80 ms)β
| Metric | Value |
|---|---|
| Runtime | 80 ms |
| Memory | N/A |
| Date | 2018-08-19 |
Solution
public class Solution {
public int RangeBitwiseAnd(int m, int n) {
if(m==0) return 0;
int moveFactor = 0;
while(m!=n)
{
m = m>>1;
n = n>>1;
moveFactor++;
}
return m<<moveFactor;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Bit Manipulation | $O(n) or O(1)$ | $O(1)$ |
Interview Tipsβ
Key Points
- Discuss the brute force approach first, then optimize. Explain your thought process.